﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWMAG.Scripting.AST.ObjectModel;
using IWMAG.Scripting.Types;
using IWMAG.Scripting.Interpreter;
using IWMAG.Scripting.Compiler.UserInfo;

namespace IWMAG.Scripting.AST.TerminalExpressions {
    internal class ValueExpression : CodeExpression {
        public ValueExpression(Compiler.Lexeme l) : base(l) { }
        protected CodeType Type;
        protected CodeExpression Cached = null;

        public override CodeType TypeOf() {
            return Type;
        }

        public override void Verify(Helpers.CompileTable sym, List<Compiler.IUserInfo> error) {
            if (!sym.Lookahead.Contains(GetType())) {
                SendError(error, Rules.ValueTokenOutsideOfLatebingExpression);
                Type = CodeType.Void;
            } else {
                Type = sym.Lookahead[GetType()]() as CodeType;
            }
        }

        public override IEnumerable<Continuation> ValueOf(Interpreter.ScriptEngine engine, Helpers.RuntimeTable sym, Interpreter.Reference<Interpreter.RunValue> val) {
            if (Cached == null) {
                Cached = sym.Passback[GetType()](null) as CodeExpression;
            }
            val.ReferencedValue.MakeLate(engine, sym, Cached);
            yield break;
        }
    }
}
